import 'package:flutter/material.dart';
import 'package:x3_base_core/base_enums/base_http_access_model_enum.dart';
import 'package:x3_base_core/base_enums/base_http_show_type_enum.dart';
import 'package:x3_base_core/base_models/base_http_request_model.dart';
import 'package:x3_base_core/base_models/base_http_response_model.dart';
import 'package:x3_base_core/base_utils/base_dio_code_util.dart';

class BaseTransformUtil {
  BaseTransformUtil._();

  ///日期或者时间戳转String
  static String dateToString({@required dateTime, bool isToLocal = true}) {
    if (dateTime == null || dateTime == "") return "";

    ///字符串类型转换成时间戳
    int _maturityTim;

    //入参
    DateTime _dateTime;

    ///格式转换
    if (dateTime.runtimeType == int) {
      ///时间戳格式
      _maturityTim = dateTime;
      _dateTime = DateTime.fromMillisecondsSinceEpoch(_maturityTim).toLocal();
    } else {
      ///字符串格式
      _maturityTim = DateTime.parse(dateTime).millisecondsSinceEpoch;
      if (isToLocal) {
        _dateTime = DateTime.parse(dateTime).toLocal();
      } else {
        _dateTime = DateTime.parse(dateTime);
      }
    }
    //当前时间
    DateTime currentTime = DateTime.now();

    ///超出一年
    if (_dateTime.year != currentTime.year) return "${format(_dateTime.year)}-" + "${format(_dateTime.month)}-" + "${format(_dateTime.day)} " + " ${format(_dateTime.hour)}:${format(_dateTime.minute)}";

    ///间隔时间 = 当前时间 - 创建时间   单位：分钟
    int _minute = currentTime.difference(_dateTime).inMinutes.abs();

    ///一小时以内
    if (_minute < 60 && _minute > 1) return "$_minute分钟前";
    if (_minute <= 1) return "刚刚";

    ///当天
    if (isToday(_maturityTim, isUtc: _dateTime.isUtc)) return "今天 ${format(_dateTime.hour)}:${format(_dateTime.minute)}";

    ///前一天 - 昨日
    if ((DateTime.now().day - _dateTime.day) == 1) return "昨天 ${format(_dateTime.hour)}:${format(_dateTime.minute)}";

    ///其的
    return "${format(_dateTime.month)}-" + "${format(_dateTime.day)} " + " ${format(_dateTime.hour)}:${format(_dateTime.minute)}";
  }

  /// 是否是当天.
  static bool isToday(int milliseconds, {bool isUtc = false, int locMs}) {
    if (milliseconds == null || milliseconds == 0) return false;
    DateTime old = DateTime.fromMillisecondsSinceEpoch(milliseconds, isUtc: isUtc);
    DateTime now;
    if (locMs != null) {
      now = DateTime.fromMillisecondsSinceEpoch(locMs, isUtc: isUtc);
    } else {
      now = isUtc ? DateTime.now().toUtc() : DateTime.now().toLocal();
    }
    return old.year == now.year && old.month == now.month && old.day == now.day;
  }

  ///距离现在的时间差是否超过24小时
  static bool isMoreThanOneDay(String time, {bool isUtc = false, int locMs}) {
    if (time == null || time == "") return false;

    ///一天
    int inMinutesSum = 24 * 60;
    DateTime dateTime = DateTime.parse(time);
    DateTime now;
    if (locMs != null) {
      now = DateTime.fromMillisecondsSinceEpoch(locMs, isUtc: isUtc);
    } else {
      now = isUtc ? DateTime.now().toUtc() : DateTime.now().toLocal();
    }

    ///间隔时间 = 当前时间 - 创建时间   单位：分钟
    int _minute = now.difference(dateTime).inMinutes.abs();
    if (_minute > inMinutesSum) return true;
    return false;
  }

  /// Date 转 String
  static String dateTimeAsString(DateTime dateTime) {
    return dateTime.toIso8601String() + '+0800';
  }

  /// String 转 Date
  static DateTime stringAsDateTime({@required String date}) {
    String timeText = date;
    if (timeText.contains("+0800")) {
      timeText = timeText.split('+0800')[0];
    }
    return DateTime.tryParse(timeText);
  }

  /// String 转 Date
  static String stringToDate(String str, {String symbol = '-'}) {
    if (str == null || str.length == 0) {
      return '';
    }
    try {
      DateTime date = DateTime.parse(str).toLocal();
      return '${date.year.toString()}$symbol${date.month.toString().padLeft(2, '0')}$symbol${date.day.toString().padLeft(2, '0')}';
    } catch (e) {
      return str;
    }
  }

  /// String 转 TimeStamp
  static String stringToDateTimeStamp(String str, {bool isToLocal = true, bool isNeedShowSecond = true, bool isNeedNotShowTime = false}) {
    if (str == null || str.length == 0) {
      return '';
    }
    try {
      Duration timeZoneOffset = DateTime.now().timeZoneOffset;
      DateTime date;
      if (isToLocal) {
        date = DateTime.parse(str).toLocal();
      } else {
        date = DateTime.parse(str);
      }
      if (isNeedShowSecond == true) {
        return '${date.year}-${format(date.month)}-${format(date.day)} ${format(date.hour)}:${format(date.minute)}:${format(date.second)}';
      }
      if (isNeedNotShowTime) {
        return '${date.year}-${format(date.month)}-${format(date.day)}';
      }
      return '${date.year}-${format(date.month)}-${format(date.day)} ${format(date.hour)}:${format(date.minute)}';
    } catch (e) {
      return str;
    }
  }

  /// String日期 转 时间
  static String stringToTimeStamp(String str, {bool isNeedShowSecond = true}) {
    if (str == null || str.length == 0) {
      return '';
    }
    try {
      Duration timeZoneOffset = DateTime.now().timeZoneOffset;
      DateTime date = DateTime.parse(str).add(timeZoneOffset);
      if (isNeedShowSecond == true) {
        return '${format(date.hour)}:${format(date.minute)}:${format(date.second)}';
      }
      return '${format(date.hour)}:${format(date.minute)}';
    } catch (e) {
      return str;
    }
  }

  /// 把 9 -> 09
  static format(int num) {
    return num < 10 ? '0$num' : num;
  }

  /// 添加分隔符 默认千分位
  static String formatNumAddDelimiter(num, {point: 3}) {
    if (num != null && double.tryParse(num.toString()) != null) {
      String str = double.parse(num.toString()).toString();
      // 分开截取
      List<String> sub = str.split('.');
      // 处理值
      List val = List.from(sub[0].split(''));
      //处理分割符
      for (int index = 0, i = val.length - 1; i >= 0; index++, i--) {
        // 除以三没有余数、不等于零并且不等于1 就加个逗号
        if (index % 3 == 0 && index != 0) val[i] = val[i] + ',';
      }
      return val.join('');
    } else {
      return "0";
    }
  }

  /// 枚举值 转String字符串
  static String enumToString(o) => o.toString().split('.').last;

  /// String 转枚举值
  static T enumFromString<T>(Iterable<T> values, String value) {
    return values.firstWhere((type) => type.toString().split('.').last == value, orElse: () => null);
  }

  /// 匹配接口 { } 里的字符串并填充数据
  static String matchServiceUrl(String inputApi, dynamic params) {
    if (inputApi.contains('{') && inputApi.contains('}') && params.isNotEmpty) {
      RegExp exp = new RegExp(r"(\w+)");
      List<Match> expMatch = exp.allMatches(inputApi).toList();
      expMatch.forEach((element) {
        String word = element.group(0);
        if (inputApi.contains('{$word}')) {
          dynamic data = params[word] ?? '0';
          inputApi = inputApi.replaceAll('{$word}', data);
        }
      });
      return inputApi;
    }
    return inputApi;
  }

  /// 获取出参中的 accessMode 不为 WebHidden 的列
  static List<BaseHttpResponseModel> getShowResponseModels(List<BaseHttpResponseModel> result) {
    if (result == null) return [];
    return result.where((element) => element.accessMode != enumToString(BaseHttpAccessModelEnum.WebHidden)).toList();
  }

  /// 获取入参中的 accessMode 不为 WebHidden 的列
  static List<BaseHttpRequestModel> getShowRequestModels(List<BaseHttpRequestModel> result) {
    if (result == null) return [];
    return result.where((element) => element.accessMode.toString() != enumToString(BaseHttpAccessModelEnum.WebHidden)).toList();
  }

  /// 获取出参中的 指定 showType 的列
  static List<BaseHttpResponseModel> getDesignatedResponseModelsByShowType(List<BaseHttpResponseModel> result, BaseHttpShowTypeEnum showTypeEnum) {
    if (result == null) return [];
    return result.where((element) => element.showType == enumToString(showTypeEnum)).toList();
  }

  /// 获取出参中的 指定 fieldName 的列
  static List<BaseHttpResponseModel> getDesignatedResponseModelsByFieldName(List<BaseHttpResponseModel> result, String fieldName) {
    if (result == null) return [];
    return result.where((element) => element.fieldName == fieldName).toList();
  }

  /// 获取入参中的 指定 fieldName 的列
  static List<BaseHttpRequestModel> getDesignatedRequestModelsByFieldName(List<BaseHttpRequestModel> result, String fieldName) {
    if (result == null) return [];
    return result.where((element) => element.fieldName == fieldName).toList();
  }

  /// 把List<dynamic>集合数据转成List<BaseHttpResponseModel>集合数据
  static List<BaseHttpResponseModel> transformToListResponseData(List<dynamic> data) {
    List<BaseHttpResponseModel> responses = [];
    List<Map<String, dynamic>> maps = BaseDioCodeUtil.dynamicListToMapList(data);
    for (int i = 0; i < maps.length; i++) {
      Map<String, dynamic> json = maps[i];
      BaseHttpResponseModel model = BaseHttpResponseModel.fromJson(json);
      responses.add(model);
    }
    return responses;
  }

  /// 把List<dynamic>集合数据转成List<BaseHttpRequestModel>集合数据
  static List<BaseHttpRequestModel> transformToListRequestData(List<dynamic> data) {
    List<BaseHttpRequestModel> requests = [];
    List<Map<String, dynamic>> maps = BaseDioCodeUtil.dynamicListToMapList(data);
    for (int i = 0; i < maps.length; i++) {
      Map<String, dynamic> json = maps[i];
      BaseHttpRequestModel model = BaseHttpRequestModel.fromJson(json);
      requests.add(model);
    }
    return requests;
  }

  /// 字符串变color
  static Color transformColor(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll("#", "");
    hexColor = hexColor.replaceAll('0X', '');
    if (hexColor.length == 6) {
      hexColor = "FF" + hexColor;
    }
    return Color(int.parse(hexColor, radix: 16));
  }

  ///  string 转 double
  static double stringToDouble(String value) {
    return double.parse(value);
  }

  /// 列表转为字符串 List<String> to ""
  static String listToString({@required List<String> list, String interval = ''}) {
    if (list == null || list.length == 0) return '';
    String _text = '';
    list.asMap().keys.forEach((index) {
      if (index == 0) _text += list[0];
      if (index != 0) _text += '$interval${list[index]}';
    });
    return _text;
  }

  /// 字符串转为列表 "" to List<String>
  static List<String> stringToList({@required String text, String interval = ''}) {
    if (text == null || text.isEmpty) return [];
    List<String> _list = text.split(interval);
    return _list;
  }
}
